from peewee import *
from src.models.BaseModel import BaseModel
from src.util.Model2Dict import m2d
from src.entry.Entrys import Page

""" 组 """


class Group(BaseModel):
    id = BigIntegerField(primary_key=True)
    name = CharField()
    status = CharField()
    createBy = BigIntegerField(db_column='create_by')
    createTime = DateTimeField(db_column='create_time')
    updateBy = BigIntegerField(db_column='update_by')
    updateTime = DateTimeField(db_column='update_time')
    description = CharField()

    class Meta:
        table_name = "sys_group"

    # 查询组
    @staticmethod
    def getGroupAll(page: Page = Page(), cdn: dict = None):
        if cdn is None:
            cdn = dict()
        query = Group.select()
        if cdn.get('status'):
            query = query.where(Group.status == cdn.get('status'))
        if cdn.get('name'):
            query = query.where(Group.name.contains(cdn.get('name')))
        if cdn.get('createTime'):
            t: list[str] = cdn.get('createTime')
            if t[0]:
                query = query.where(Group.createTime > t[0])
            if t[1]:
                query = query.where(Group.createTime < t[1])
        if cdn.get('order'):
            order: dict = cdn.get('order')
            if order.get('createTime') and order.get('createTime') == 'asc':
                query = query.order_by(Group.createTime.asc())
            if order.get('createTime') and order.get('createTime') == 'desc':
                query = query.order_by(Group.createTime.desc())
        r = query.paginate(page.num, page.size).dicts()
        page.count = query.count()
        page.rows = m2d(r)
        return page.__dict__

    # 根据用户组id 查询用户组信息
    @staticmethod
    def getOneById(g_id: int) -> dict | None:
        q = Group.select().where(Group.id == g_id)
        data = m2d(q.dicts())
        if len(data) > 0:
            return data[0]
        return None

    # 删除组
    @staticmethod
    def delGroup(ids: list[int]):
        Group.delete().where(Group.id.in_(ids)).execute()
        return True

    # 添加组
    @staticmethod
    def addGroup(data: dict):
        return Group.insert(data).execute()

    # 更新组
    @staticmethod
    def updateGroup(data: dict):
        Group.update(data).where(Group.id == data.get('id')).execute()
        return True


#    组里的用户列表
class GroupUser(BaseModel):
    gid = BigIntegerField()
    uid = BigIntegerField()

    class Meta:
        table_name = "sys_group_user"

        # 查询组的用户

    @staticmethod
    def getGroupUserByGid(gid: int):
        data = GroupUser.select(GroupUser.uid).where(GroupUser.gid == gid).dicts()
        return [item.get('uid') for item in m2d(data)]

    # 查询用户的组
    @staticmethod
    def getUserGroupByUid(gid: int):
        data = GroupUser.select(GroupUser.gid).where(GroupUser.uid == gid).dicts()
        return [item.get('gid') for item in m2d(data)]

    # 删除某组的所有用户
    @staticmethod
    def delGroupUserInGid(gid: list[int]):
        GroupUser.delete().where(GroupUser.gid.in_(gid)).execute()
        return True

    # 给某个组添加用户
    @staticmethod
    def addGroupUser(ids: list[int], gid: int):
        data = [{'gid': gid, 'uid': item} for item in ids]
        GroupUser.insert_many(data).execute()
        return True

    # 检查用户组是否有某用户
    @staticmethod
    def hasUser(g_id: list[int], u_id: int):
        q = GroupUser.select(GroupUser.uid)
        q = q.where(GroupUser.gid.in_(g_id), GroupUser.uid == u_id)
        return q.count() > 0


#   组拥有的权限
class GroupAuth(BaseModel):
    group = BigIntegerField()
    type = BigIntegerField()
    auth = CharField()

    class Meta:
        table_name = "sys_group_auth"

    # 获取某个组的某类权限列表
    @staticmethod
    def getAuth(gid: list[int], a_type: str):
        data = GroupAuth.select(GroupAuth.auth).where(GroupAuth.group.in_(gid),
                                                      GroupAuth.type == a_type).dicts()
        return [item.get('auth') for item in m2d(data)]

    # 删除某组的某类权限
    @staticmethod
    def delAuth(g_id: int, a_type: str):
        GroupAuth.delete().where(GroupAuth.group == g_id, GroupAuth.type == a_type).execute()
        return True

    # 根据 auth 以及 type 字段删除 删除 权限
    @staticmethod
    def delAuthByTypeAndAuth(auth: list[str | int], a_type: str):
        auth = [str(item) for item in auth]
        GroupAuth.delete().where(GroupAuth.auth.in_(auth), GroupAuth.type == a_type).execute()
        return True

    # 用户组权限清空
    @staticmethod
    def clearAuth(g_id: list[int]):
        GroupAuth.delete().where(GroupAuth.group.in_(g_id)).execute()
        return True

    # 添加某组某类权限
    @staticmethod
    def addAuth(g_id: int, a_type: str, data: list[str]):
        data2 = [{'group': g_id, 'type': a_type, 'auth': item} for item in data]
        return GroupAuth.insert_many(data2).execute()

    # 鉴权
    @staticmethod
    def authentication(ids: list[int], a_type: str, auth: str | int):
        sql = GroupAuth.select(GroupAuth.auth)
        sql = sql.where(GroupAuth.group.in_(ids), GroupAuth.type == a_type,
                        GroupAuth.auth == auth or GroupAuth.auth == str(auth))
        return sql.count() > 0
